import { getLogoBase64String } from '@/api/file';
import { getAppDescription, getAppTitle } from '@/api/sys/admin/settings';
import { useIdentityStore } from '@/store/modules/identity';
import { usePreferenceStore } from '@/store/modules/preference';

/**
 * 应用设置
 * @param app 应用对象
 */
export async function appSetup() {
  const preferenceStore = usePreferenceStore();
  // #region 系统logo处理
  const logo = await getLogoBase64String();
  if (logo) {
    preferenceStore.setLogo(logo);
  }
  // #endregion
  // #region 系统标题处理
  const appTitle = await getAppTitle();
  if (appTitle) {
    preferenceStore.setAppTitle(appTitle, false);
  }
  // #endregion

  // #ifdef H5
  // #region 系统网站图标处理
  let $favicon = document.querySelector('link[rel="icon"]') as HTMLLinkElement;
  if ($favicon !== null) {
    $favicon.href = preferenceStore.getLogo;
  } else {
    $favicon = document.createElement('link');
    $favicon.rel = 'icon';
    $favicon.href = preferenceStore.getLogo;
    document.head.appendChild($favicon);
  }
  // #endregion
  // #region 系统网站标题处理
  let $title = document.querySelector('title') as HTMLTitleElement;
  if ($title !== null) {
    $title.text = preferenceStore.getAppTitle;
  } else {
    $title = document.createElement('title');
    $title.text = preferenceStore.getAppTitle;
    document.head.appendChild($title);
  }
  // #endregion
  // #endif

  // #region 系统描述处理
  const appDescription = await getAppDescription();
  if (appDescription) {
    if (appDescription.Description) {
      preferenceStore.setAppDescription(appDescription.Description, false);
    }
    if (appDescription.Subdescription) {
      preferenceStore.setAppSubdescription(appDescription.Subdescription, false);
    }
  }
  // #endregion

  // #region 身份认证处理 viaHeartbeats
  const identityStore = useIdentityStore();
  // 启动应用时，如果存在Token则刷新一次
  const token = identityStore.getToken;
  if (token) {
    const refreshToken = token.RefreshToken;
    if (refreshToken) {
      await identityStore.refreshToken(refreshToken, 'message');
    }
  }
  // 每5秒检测AccessToken有效期，如过期则使用RefreshToken来刷新。
  setInterval(async () => {
    // 尝试刷新AccessToken和RefreshToken
    await identityStore.tryRefreshToken();
  }, 5000);

  // 每30秒刷新授权信息
  setInterval(async () => {
    // 刷新授权信息
    await identityStore.refreshAuthInfo();
  }, 30000);
  // #endregion
}
